/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package drexel.cs544.nap.server;

import drexel.cs544.nap.NAP;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Date; 
import org.apache.log4j.Logger;

/**
 *
 * @author rch_ltp
 */
public class ClientNode { 
    private NAP.State _state;
    private int _groupID;
    private int _clientVersion;
    private int _clientID;
    private int _maxPacketSize = 1024;
    private int _windowSize = 100;
    private Date _timeout;
    
    private static final long TIMEOUT_IN_SECONDS = 60;
    
    public ClientNode(int clientID, int clientVersion, int maxPacketSize, int windowSize)
    {
        _clientID = clientID;
        _clientVersion = clientVersion;
        _state = NAP.State.Config;
        if (windowSize < _windowSize)
            _windowSize = windowSize;
        
        if (maxPacketSize < _maxPacketSize)
            _maxPacketSize = maxPacketSize;
        _timeout = new Date();
        Logger.getLogger(getClass()).info("Created client with Client ID="
                + _clientID + ", Version=" + _clientVersion + ", Window Size="
                + _windowSize + ", Max Packet Size="+ _maxPacketSize);
    }

    public int getClientID() { return _clientID; }
    public int getClientVersion() { return _clientVersion; }
    public int getMaxPacketSize() { return _maxPacketSize; }
    public int getWindowSize() { return _windowSize; }
    
    public void setGroupID(int groupID) { _groupID = groupID; }
    public int getGroupID() { return _groupID; }
    
    public NAP.State getState() { return _state; }
    public void setState(NAP.State nState) { _state = nState; }
   
    public boolean isConnected()
    {
        //Keep track of timeout
        Date dNow = new Date();
        long timeDiff  = dNow.getTime() - _timeout.getTime();
        long diffSeconds = timeDiff / 1000;
        return (diffSeconds < TIMEOUT_IN_SECONDS); //disconnect if idle for 1 minute
    }
    

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 37 * hash + this._groupID;
        hash = 37 * hash + this._clientVersion;
        hash = 37 * hash + this._clientID;
        hash = 37 * hash + this._maxPacketSize;
        hash = 37 * hash + this._windowSize;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || getClass() != obj.getClass())
            return false;
        
        ClientNode other = (ClientNode) obj;
        return (hashCode() == other.hashCode());
    }
}
